import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtIcon} from "taro-ui";
import {Image, Text, View, Block} from "@tarojs/components";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {
  RESOURCE_URL,
  POLYMERIZE_LIST,
  POLYMERIZE_LIKE_LIST,
  TARO_ENV,
  SCAN_BIND_SELLER,
  UPDATE_USER_SHARE_DATE, IDENTITY_IS_SELLER, ROOKIEGUID_TASK_RECORD
} from "../../constants/api";
import {http} from "../../utils/http";
import {user} from "../../utils/user.service";
import {GetRequest, setTempSellerId, vcmonitor} from "../../utils/tools";
import Category from "../../pages/index/template/regionalCategory/component/category";
import Share from "../../components/share/share";
import {platform} from "../../utils/platform-settting.service";
import './list.scss'
import {h5Wx} from "../../utils/h5.service";
import {getPoster} from "../../utils/poster.service";
import {lxH5Wx} from "../../utils/lx.h5.service";

export default class Index extends Component {
  state: {
    listLoading: boolean
    linkUri: any
    tableData: any
    likeData: any
    isSeller: boolean
    showPoster: boolean
    polymerize: object
  } = {
    tableData: [],
    linkUri: '',
    isSeller: false,
    showPoster: false,
    listLoading: true,
    likeData: [],
    polymerize: {},
  }

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: platform.info.platformName,
      path: this.state.linkUri
    }
  }

  async componentDidShow() {
    const isH5 = TARO_ENV === 'h5'
    Taro.showLoading({title: '加载中...'})
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return false
    }
    if (!isH5) {
      Taro.showShareMenu({
        showShareItems: ['shareAppMessage']
      })
    }
    let bindSellerId = Taro.getStorageSync('bindSellerId') || 0;
    let tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    const bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    let scene = Taro.getCurrentInstance().router.params.scene || ''
    const params = {};
    params['uuid'] = Taro.getCurrentInstance().router.params.uuid || ''
    this.uuid = params['uuid']
    const platformSet = platform.getServerSet()
    if (scene) {
      platform.scene = 0;
      scene = scene.split('_');
      if (scene[2]) {
        tempSellerIds = Number(scene[2])
      }
      if (scene[3]) {
        Taro.setStorageSync('sKey', scene[3])
      }
      if (scene[4]) {
        params['uuid'] = scene[4]
        this.uuid = scene[4]
      }
      if (platformSet.isSellerPermanentLock) {
        if (!bindSellerId) {
          bindSellerId = Number(scene[2])
        }
      } else {
        bindSellerId = Number(scene[2])
      }
    }
    if (tempSellerIds) {
      setTempSellerId(tempSellerIds)
    }
    user.bindSellerId = bindSellerId
    Taro.setStorageSync('bindSellerId', user.bindSellerId)
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, {temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds});
    }
    let isSeller = true
    if (process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      isSeller = identityIsSeller.isSeller
    }
    try {
      const res = await http.HPost(POLYMERIZE_LIST, params)
      let name = '聚合页面'
      Taro.hideLoading()
      if (res && res.data && res.data.model && res.data.model.name) {
        name = res.data.model.name
        await Taro.setNavigationBarTitle({
          title: res.data.model.name
        })
      } else {
        await Taro.setNavigationBarTitle({
          title: '聚合页面'
        })
      }
      const shareParams = await user.getSellerParam(tempSellerIds)
      this.shareParams = shareParams
      let link = `/common/polymerize/list?scene=${shareParams.sellerId || 0}_${shareParams.bindSellerId || 0}_${shareParams.tempSellerId || 0}_${Taro.getStorageSync('sKey' || '')}_${this.uuid}`
      if (isH5) {
        link = window.location.origin + link
        const shareData = {
          title: platformSet.platformName,
          desc: name,
          link,
          imgUrl: platformSet.platformLogo
        }
        h5Wx.share(shareData)
      }
      res && this.setState({tableData: res.data.list, polymerize: res.data.model})
      const likeRes = await http.HGet(POLYMERIZE_LIKE_LIST, params)
      likeRes && this.setState({likeData: likeRes.data})
      this.setState({listLoading: false, isSeller, linkUri: link})
    } catch (e) {
      this.setState({listLoading: false})
      Taro.hideLoading()
    }
  }

  uuid
  shareParams
  posterUrl

  jump(urlBegin, e) {
    e.stopPropagation()
    let scene = Taro.getCurrentInstance().router.params.scene || ''
    let url = urlBegin
    if (scene) {
      platform.scene = 0
      scene = scene.split('_')
      if (scene[0]) {
        url += '&sellerId=' + scene[0]
      }
      if (scene[1]) {
        url += '&bindSellerId=' + scene[1]
      }
      if (scene[2]) {
        url += '&tempSellerId=' + scene[2]
      }
    }
    const uInfo = Taro.getStorageSync('user') || ''
    if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
      url += '&mpkey=' + uInfo.mpkey
    }
    Taro.navigateTo({ url });
  }

  async savePhoto() {
    Taro.showLoading({title: '保存中...'})
    await Taro.getImageInfo({
      src: this.posterUrl
    }).then(async (res) => { // 需要同步处理，否则会因为异步导致写入资源繁忙，无法保存
      await Taro.saveImageToPhotosAlbum({
        filePath: res.path,
      }).then(() => {
        Taro.hideLoading()
        Taro.showToast({title: '已保存1张图片'})
      }).catch(err => {
        Taro.hideLoading()
        console.log(err);
      })
    }).catch(err => {
      Taro.hideLoading()
      console.log(err);
    })
  }

  imgClick() {
    Taro.previewImage({
      current: this.posterUrl,
      urls: [this.posterUrl]
    })
  }

  async onHandlerShowDialog() {
    try {
      Taro.showLoading({title: '加载中...'})
      const poster = await getPoster('polymerize', this.uuid, `/common/polymerize/list?scene=${this.shareParams.sellerId || 0}_${this.shareParams.bindSellerId || 0}_${this.shareParams.tempSellerId || 0}_${Taro.getStorageSync('sKey' || '')}_${this.uuid}`)
      user.checkLogin().then(isLogin => {
        if (isLogin) {
          http.HPost(ROOKIEGUID_TASK_RECORD, {remark: "保存海报"})
        }
      })
      if (poster && poster.url) {
        Taro.hideLoading()
        lxH5Wx.setShare(platform.info.platformName, poster.url)
      }
    } catch (e) {
      Taro.hideLoading()
    }
  }

  render() {
    const dataColor = Taro.getStorageSync('colorData');
    const scene = Taro.getCurrentInstance().router.params.scene || ''
    const {tableData, likeData, polymerize, showPoster, listLoading, linkUri, isSeller} = this.state
    return (
      <View className='list-root' style={`background: ${polymerize.color};`}>
        <GzhAuth />
        {tableData && tableData.length > 0 &&
        <View className='bg' style={`background: url(${polymerize.photo}) no-repeat; `} />}
        {tableData && tableData.length > 0 && <View className='item'>
          {tableData.map(item =>
            <View className='items'key={item.uuid} onClick={this.jump.bind(this, item.url)}>
              <View><Image src={item.img} mode='widthFix' className='img' /></View>
              <View className='pro-name'>{item.name}</View>
              {!!item.sub_title && <View className='pro-sub-title pro-sub-title-big-top'>{item.sub_title}</View>}
              {!!platform.info.is_show_sales_volume && !!item.salesVolume &&
              <View className='salesVolume'>销量：{item.salesVolume}笔</View>}
              <View className='right-price'>
                <View className='price left-price'>
                  <Text className={`font-family-price m-min-b ${!!item.discount && 'm-big-b'}`}
                    style={`color: ${dataColor.priceColor}`}
                  >￥</Text>
                  <Text className={`font-family-price true-price m-min-b ${!!item.discount && 'm-big-b'}`}
                    style={`color: ${dataColor.priceColor}`}
                  >{item.price}</Text>
                  {!!item.discount && <Text className='font-family-price discount'>{item.discount}折</Text>}
                  <View className='font-family-price price-right m-min-b'
                    style={`color: ${dataColor.originalPriceColor}`}
                  >
                    <Text>￥{item.market_price}</Text>
                    <View className='line' style={`background-color: ${dataColor.originalPriceColor}`} />
                  </View>
                </View>
                {(isSeller || !item.commission_price) &&
                <View className='snapped-up'
                  onClick={this.jump.bind(this, item.url)}
                >{item.is_activity == 1 ? '立即拼团' : '立即抢购'}</View>}
                {!isSeller && <Block>
                  {!!item.commission_price && <View className='share-earn'>
                    <View className='share-left'>分享赚</View>
                    <View className='price'><Text className='true-price-share'>￥</Text><Text
                      className='true-price-share'
                    >{item.commission_price}</Text></View>
                  </View>}
                </Block>}
              </View>
            </View>
          )}
        </View>}
        {likeData && likeData.length > 0 && <View className='recommend'>
          <View className='recommend-box'>
            <Image mode='aspectFill' className='img'
              src='https://resource.ivcheng.com/upload/images/20210824/1629774393510_118.png'
            />
            <View className='name'>你可能还喜欢</View>
            <Image mode='aspectFill' className='img'
              src='https://resource.ivcheng.com/upload/images/20210824/1629774381270_201.png'
            />
          </View>
          <View>
            <Category data={likeData} isUser={isSeller} scene={scene} />
          </View>
        </View>
        }
        {process.env.P_ENV === 'lx' && <View className='share-settings-components-logo share-settings-components-logo-big-bottom' onClick={() => Taro.navigateTo({url: '/main/order/order'})}><Image mode='widthFix' className='share-settings-components-logo-img' src={RESOURCE_URL + '/resources/images/myorder.png'} /></View>}
        {linkUri && <Share isUser={!isSeller} displayPoster type='polymerize' linkUri={linkUri} uuid={this.uuid} onHandlerShowDialog={()=>{ this.onHandlerShowDialog() }} />}
        {likeData.length <= 0 && tableData.length <= 0 && !listLoading && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
          <View className='text'>什么都没有,去看看别的吧~</View>
        </View>}
        {showPoster && <View className='share-poster'>
          <View className='share-poster-bg' />
          <View className='share-poster-container'>
            <View className='share-poster-body'>
              <View onClick={() => this.setState({showPoster: false})} className='share-poster-close'>
                <AtIcon value='close-circle' size='24' color='#fff' />
              </View>
              <View onClick={this.imgClick.bind(this)}>
                <Image className='gzh-close-img' src={this.posterUrl} mode='widthFix' />
              </View>
              <View className='saveToPhoto-box' onClick={this.savePhoto.bind(this)}>
                {TARO_ENV === 'weapp' ? <View className='saveToPhoto'>保存到相册</View> :
                  <View className='saveToPhoto'>请长按图片保存至相册</View>}
              </View>
            </View>
          </View>
        </View>}
      </View>
    )
  }
}
